package com.formula.datastructure.exam.sort;

import com.formula.datastructure.util.DataUtil;

public class InsertBinSort {

    public Integer[] sort(Integer[] array) {
        int low;
        int high;
        int mid;

        for (int i = 1; i < array.length; i++) {
            Integer insert = array[i];
            low = 0;
            high = i;

            while (low <= high) {
                mid = (low + high) / 2;
                if (array[mid] == insert) {
                    high = mid;
                    break;
                }
                if (insert > array[mid]) {
                    low = mid + 1;
                } else {
                    high = mid - 1;
                }
            }

            for (int j = i - 1; j > high; j--) {
                array[j + 1] = array[j];
            }
            array[high + 1] = insert;
        }

        return array;
    }

    public static void main(String[] args) {
        InsertBinSort bin = new InsertBinSort();
        int size = 20;
        int range = 999;
        Integer[] array = DataUtil.genUniqueArray(size, range);
        DataUtil.printIndex(size);
        DataUtil.printArray(array);
        DataUtil.printArray(bin.sort(array));
    }
}
